package com.crowntit.service.impl;

import com.crowntit.service.ILoginService;
import com.crowntit.domain.req.WeixinQrCodeReq;
import com.crowntit.domain.res.WeixinQrCodeRes;
import com.crowntit.domain.res.WeixinTokenRes;
import com.crowntit.service.weixin.IWeixinApiService;
import com.google.common.cache.Cache;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import retrofit2.Call;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class LoginServiceImpl implements ILoginService {

    @Value("${weixin.config.app-id}")
    private String appid;
    @Value("${weixin.config.app-secret}")
    private String appSecret;

    @Resource
    private Cache<String, String> weixinAccessToken;
    @Resource
    private IWeixinApiService iWeixinApiService;
    @Resource
    private Cache<String, String> openidToken;

    @Override
    public String createQrCode() throws IOException {
        // 1. 获取access token
        String accessToken = weixinAccessToken.getIfPresent(appid);
        if (accessToken == null){
            // 申请access token
            Call<WeixinTokenRes> call = iWeixinApiService.getToken("client_credential", appid, appSecret);
            WeixinTokenRes tokenRes = call.execute().body();
            assert tokenRes != null;
            accessToken = tokenRes.getAccess_token();
            weixinAccessToken.put(appid, accessToken);
        }

        // 2. 生成ticket
        WeixinQrCodeReq weixinQrCodeReq = WeixinQrCodeReq.builder()
                .expire_seconds(2592000)
                .action_name(WeixinQrCodeReq.ActionNameTypeVO.QR_SCENE.getCode())
                .action_info(WeixinQrCodeReq.ActionInfo.builder()
                        .scene(WeixinQrCodeReq.ActionInfo.Scene.builder()
                                .scene_id(100601)
                                .build())
                        .build())
                .build();

        Call<WeixinQrCodeRes> call = iWeixinApiService.createQrCode(accessToken, weixinQrCodeReq);
        WeixinQrCodeRes qrCodeRes = call.execute().body();
        assert qrCodeRes != null;
        return qrCodeRes.getTicket();
    }

    @Override
    public String checkLogin(String ticket) {
        return openidToken.getIfPresent(ticket);
    }
}
